package com.itheima.cs.common.dyewm;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.StringUtils;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.itheima.cs.MainActivity;
import com.itheima.cs.R;
import com.itheima.cs.common.CustomCaptureActivity;
import com.itheima.cs.common.nbdb.InternalTransferFormActivity;
import com.itheima.cs.dao.MaterialDao;
import com.itheima.cs.entity.dyewm.MaterialInfo;
import com.itheima.cs.utils.BluetoothUtil;
import com.itheima.cs.utils.LoginManager;
import com.itheima.cs.utils.UuidGenerator;
import com.sunmi.printerx.PrinterSdk;
import com.sunmi.printerx.SdkException;
import com.sunmi.printerx.api.CanvasApi;
import com.sunmi.printerx.api.PrintResult;
import com.sunmi.printerx.enums.Align;
import com.sunmi.printerx.enums.ErrorLevel;
import com.sunmi.printerx.enums.Shape;
import com.sunmi.printerx.style.AreaStyle;
import com.sunmi.printerx.style.BaseStyle;
import com.sunmi.printerx.style.QrStyle;
import com.sunmi.printerx.style.TextStyle;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class PrintQRCodeActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int REQUEST_SELECT_MATERIAL = 1001;
    // 使用GBK编码
    private static final Charset GBK_CHARSET = Charset.forName("GBK");
    @SuppressLint("SimpleDateFormat")
    private SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd");
    @SuppressLint("SimpleDateFormat")
    private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
    private Button btn_scan,btnPrint;
    private EditText editTextSearch;
    private Handler mainHandler;
    private MaterialInfo selectedMaterial;
    private BluetoothSocket socket;
    private BluetoothAdapter btAdapter;
    public PrinterSdk.Printer selectPrinter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_print_qrcode);

//        btAdapter = BluetoothUtil.getBTAdapter();
//        if (btAdapter == null) {
//            showToast("蓝牙不可用");
//        } else {
//            connectPrinter();
//        }

        initView();

        initPrinter();
    }

    private void initView(){
        btn_scan = findViewById(R.id.btn_scan);
        editTextSearch = findViewById(R.id.editText_search);

        editTextSearch.requestFocus();

        editTextSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                String input = s.toString();
                if (!TextUtils.isEmpty(input)) {
                    handleScanResult(input);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mainHandler = new Handler(getMainLooper());

        btn_scan.setOnClickListener(this);

        Button btnSelect = findViewById(R.id.btn_select_material);
        btnSelect.setOnClickListener(v -> {
            Intent intent = new Intent(PrintQRCodeActivity.this, MaterialSelectActivity.class);
            startActivityForResult(intent, REQUEST_SELECT_MATERIAL);
        });


        Toolbar toolbar = findViewById(R.id.toolbar_print_qrcode);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnPrint = findViewById(R.id.btn_print);
        btnPrint.setVisibility(View.GONE);

    }


    public void onClick(View v) {
        switch (v.getId()){


            case R.id.btn_scan:{
                doScan();
                break;
            }


        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_SELECT_MATERIAL && resultCode == RESULT_OK) {
            MaterialInfo material = data.getParcelableExtra("selected_material");
            showMaterialResult(material);
        }

        // ZXing库中用于处理扫码结果的回调方法，主要用于解析ActivityResult对象、获取扫描结果并返回解码后的字符串。开发者需要在onActivityResult回调中调用此方法
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            handleScanResult(result);
        }

    }

    private void handleScanResult(IntentResult result) {
        if (result != null && result.getContents() != null) {
            handleScanResult(result.getContents());
        }
    }

    private void handleScanResult(String rawInput) {
        if (TextUtils.isEmpty(rawInput)) return;

        String rawInputTrim = rawInput.trim();
        if (rawInputTrim.isEmpty()) return;

        String[] rawInputArray = rawInputTrim.split(",");
        if (rawInputArray.length != 2) return;

        String materialCode = rawInputArray[0];
        String dbdUUID = rawInputArray[1];
        if (materialCode.isEmpty() || dbdUUID.isEmpty()) return;

        new MaterialQueryTask().execute(materialCode);
    }

    private class MaterialQueryTask extends AsyncTask<String, Void, MaterialInfo> {

        @Override
        protected MaterialInfo doInBackground(String... params) {
            MaterialDao dao = new MaterialDao();
            return dao.getMaterialByCode(params[0]);
        }

        @Override
        protected void onPostExecute(MaterialInfo materialInfo) {
            if (materialInfo != null && !TextUtils.isEmpty(materialInfo.getCode())) {

                Intent intent = new Intent(PrintQRCodeActivity.this, ScanResultActivity.class);
                intent.putExtra("code", materialInfo.getCode());
                intent.putExtra("name", materialInfo.getName());
                intent.putExtra("spec", materialInfo.getSpec());
                startActivity(intent);
            } else {

                Toast.makeText(PrintQRCodeActivity.this,
                        "物料编码不存在" + (materialInfo == null ? "" : materialInfo.getCode()),
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void doScan(){
        IntentIntegrator intentIntegrator = new IntentIntegrator(this);
        intentIntegrator.setCaptureActivity(CustomCaptureActivity.class);
        intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
        intentIntegrator.setPrompt("请对准二维码");
        intentIntegrator.setCameraId(0);
        intentIntegrator.setBeepEnabled(false);
        intentIntegrator.setBarcodeImageEnabled(false);
        intentIntegrator.setOrientationLocked(true);
        intentIntegrator.initiateScan();
    }

    private void showPrintButton() {
        Button btnPrint = findViewById(R.id.btn_print);
        btnPrint.setVisibility(View.VISIBLE);

        btnPrint.setOnClickListener(v -> {
            if (selectedMaterial != null) {
                String qrContent = selectedMaterial.getCode();
                // 打印内容是：物料编码,UUID
                String dbdUUID = UuidGenerator.generateCompactUuid();
                String printContent = qrContent.concat(",").concat(dbdUUID);
//                printQRCode(qrContent);
                String username = LoginManager.getInstance(PrintQRCodeActivity.this).getUsername();
                StringBuilder headBuilder = new StringBuilder();
                headBuilder.append("物料名称：").append(selectedMaterial.getName()).append("\n")
                                .append("物料编码：").append(selectedMaterial.getCode()).append("\n")
                                .append("规格型号：").append(selectedMaterial.getSpec()).append("\n\n");
                StringBuilder footerBuilder = new StringBuilder();
                footerBuilder.append("赋码用户：").append(username).append("\n").append("日期：").append(dataFormat.format(new Date())).append("\n\n");
                //外置设备调用sunmi打印机
//                printQRCodeWithTitle(printContent,headBuilder.toString(),footerBuilder.toString());
                //内置调用sunmi打印机
                printQRCodeWithInnerPrint(printContent,selectedMaterial.getName(),selectedMaterial.getCode(),selectedMaterial.getSpec(),username);
            } else {
                Toast.makeText(this, "未选择物料", Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void connectPrinter() {
        try {
            if (socket != null) {
                socket.close();
            }
            BluetoothDevice device = BluetoothUtil.getDevice(btAdapter);
            if (device == null) {
                showToast("未找到打印机");
                return;
            }
            socket = device.createRfcommSocketToServiceRecord(
                    UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
            socket.connect();
        } catch (IOException e) {
            showToast("连接失败: " + e.getMessage());
            socket = null;
        }
    }

    /**
     * 调用sunmi内置打印机方式进行打印
     */
    private void printQRCodeWithInnerPrint(String qrCodeData, String materialName,
                                           String materialCode, String materialSpe, String username) {

        try {
//            CanvasApi api = ((MainActivity)getActivity()).selectPrinter.canvasApi();
//            CanvasApi api = MainActivity.selectPrinter.canvasApi();
            CanvasApi api = selectPrinter.canvasApi();
            //调整整体
            api.initCanvas(BaseStyle.getStyle().setWidth(580).setHeight(440));
            //调整虚线框
            api.renderArea(AreaStyle.getStyle().setStyle(Shape.BOX).setPosX(0).setPosY(0).setWidth(385).setHeight(360));
            api.renderText("物料名称："+materialName, TextStyle.getStyle().setTextSize(32).enableBold(true)
                    .setPosX(30).setPosY(25));
            api.renderText("物料编码："+materialCode, TextStyle.getStyle().setTextSize(25).setPosX(10).setPosY(70));
            int indexOfSpe = 5;
            if (materialSpe.length()>19) {
                api.renderText("规格型号："+materialSpe.substring(0, 19), TextStyle.getStyle().setTextSize(25).setPosX(10).setPosY(105));
                api.renderText(materialSpe.substring(19), TextStyle.getStyle().setTextSize(25).setPosX(10).setPosY(130));
                indexOfSpe=30;
            } else {
                api.renderText("规格型号："+materialSpe, TextStyle.getStyle().setTextSize(25).setPosX(10).setPosY(105));
            }
            api.renderQrCode(qrCodeData,
                    QrStyle.getStyle().setDot(3).setPosX(35).setPosY(140+indexOfSpe).setWidth(180).setHeight(180).setAlign(Align.CENTER).setErrorLevel(ErrorLevel.H));
//            api.renderText("赋码用户："+username, TextStyle.getStyle().setTextSize(30).setPosX(30).setPosY(360+indexOfSpe));
            api.renderText(username, TextStyle.getStyle().setTextSize(25).setPosX(230).setPosY(160+indexOfSpe));
//            api.renderText("日期："+format.format(new Date()), TextStyle.getStyle().setTextSize(28).setPosX(10).setPosY(400+indexOfSpe));
            api.renderText(dataFormat.format(new Date()), TextStyle.getStyle().setTextSize(25).setPosX(230).setPosY(190+indexOfSpe));
            api.renderText(timeFormat.format(new Date()), TextStyle.getStyle().setTextSize(25).setPosX(230).setPosY(220+indexOfSpe));
//            api.renderText("", TextStyle.getStyle().setTextSize(30).setPosX(10).setPosY(440+indexOfSpe));
            api.renderText("", TextStyle.getStyle().setTextSize(20).setPosX(10).setPosY(330+indexOfSpe));
            api.printCanvas(1, new PrintResult() {
                @Override
                public void onResult(int resultCode, String message) throws RemoteException {
                    if(resultCode == 0) {
                        //打印完成
                        showToast("打印成功");
                    } else {
                        //打印失败
                        showToast("打印失败");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化连接summi内置打印机
     */
    private void initPrinter() {
        try {
            PrinterSdk.getInstance().getPrinter(this, new PrinterSdk.PrinterListen() {
                @Override
                public void onDefPrinter(PrinterSdk.Printer printer) {
                    selectPrinter = printer;
                }

                @Override
                public void onPrinters(List<PrinterSdk.Printer> printers) {

                }
            });
        } catch (SdkException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PrinterSdk.getInstance().destroy();
    }

    /**
     * 外置蓝牙设备连接sunmi打印机进行打印
     */
    private void printQRCodeWithTitle(String data, String title, String footer) {
        OutputStream os = null;
        try {
            btAdapter = BluetoothUtil.getBTAdapter();
            if (btAdapter == null) {
                showToast("蓝牙不可用");
            } else {
                connectPrinter();
            }
            Bitmap resultBitmap = getQRBitmap(data);
//            sendToPrinter(bytes);
            showToast("打印指令已发送");
            os = socket.getOutputStream();
            printBitmap(resultBitmap, os, title, footer);
//            os.write(data);
//            os.flush();
            Thread.sleep(200);

        } catch (Exception e) {
            handleException(e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                    os=null;
                } catch (IOException e) {
                    handleException(e);
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                    socket=null;
                } catch (IOException e) {
                    handleException(e);
                }
            }
        }

    }

    private Bitmap getQRBitmap(String data) throws WriterException {
        int width = 300;
        int height = 300;
        BitMatrix result = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height);
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                bitmap.setPixel(x, y, result.get(x, y) ? Color.BLACK : Color.WHITE);
            }
        }
//        // 创建带标题的完整图片
//        int titleHeight = title.isEmpty() ? 0 : 60; // 标题区域高度
//        int padding = 20; // 内边距

        // 创建新画布（二维码高度 + 标题高度）
//        Bitmap resultBitmap = Bitmap.createBitmap(
//                width,
//                height + titleHeight,
//                Bitmap.Config.ARGB_8888
//        );
//        Canvas canvas = new Canvas(resultBitmap);
//
//        // 绘制白色背景
//        canvas.drawColor(Color.WHITE);
//
//        // 绘制标题（如果有）
//        if (!title.isEmpty()) {
//            Paint titlePaint = new Paint();
//            titlePaint.setColor(Color.BLACK);
//            titlePaint.setTextSize(36);
//            titlePaint.setTypeface(Typeface.DEFAULT_BOLD);
//            titlePaint.setTextAlign(Paint.Align.CENTER);
//
//            // 计算标题位置
//            float titleX = width / 2f;
//            float titleY = titleHeight - padding;
//            canvas.drawText(title, titleX, titleY, titlePaint);
//        }
//
//        // 绘制二维码
//        canvas.drawBitmap(bitmap, 0, titleHeight, null);
        return bitmap;
    }
    private void printQRCode(String data) {
        try {
            if (!checkConnection()) return;

            byte[] init = {0x1B, 0x40};
            byte[] alignLeft = {0x1B, 0x61, 0x00};
            byte[] qrModel = {0x1D, 0x28, 0x6B, 0x04, 0x00, 0x31, 0x41, 0x32, 0x00};
            byte[] qrSize = {0x1D, 0x28, 0x6B, 0x03, 0x00, 0x31, 0x43, 0x08};
            byte[] qrECLevel = {0x1D, 0x28, 0x6B, 0x03, 0x00, 0x31, 0x45, 0x31};
            byte[] dataBytes = data.getBytes("UTF-8");
            byte[] qrDataHeader = {
                    0x1D, 0x28, 0x6B,
                    (byte) (dataBytes.length + 3), 0x00,
                    0x31, 0x50, 0x30
            };
            byte[] qrPrint = {0x1D, 0x28, 0x6B, 0x03, 0x00, 0x31, 0x51, 0x30};

            byte[] feedAfter = {0x1B, 0x64, 0x05};

            byte[] bytes = concatBytes(
                    init,
                    alignLeft,
                    qrModel,
                    qrSize,
                    qrECLevel,
                    qrDataHeader,
                    data.getBytes("UTF-8"),
                    qrPrint,
                    feedAfter
            );

            sendToPrinter(bytes);
            showToast("打印指令已发送");
        } catch (Exception e) {
            handleException(e);
        }
    }

    private void printBitmap(Bitmap bitmap, OutputStream outputStream,String title, String footer) throws IOException {
        // 1.打印机初始化
        outputStream.write(new byte[]{0x1B, 0x40}); // ESC @ 初始化

//         2. 设置UTF-8编码
//        setUtf8Encoding(outputStream);
        // 2. 设置GBK编码
        setGbkEncoding(outputStream);

        // 3. 打印页眉文本（可选）
//        printText("二维码打印\n", true, true, outputStream);
        // 向右偏移2个字符位置打印页眉
        printTextWithOffset(title, 2, false, false, outputStream);

        // 4. 打印二维码图片
        outputStream.write(new byte[]{0x1B, 0x61, 0x00}); // 左对齐
        // 设置行间距为0
        outputStream.write(new byte[]{0x1B, 0x33, 0x00});

        // 光栅位图模式
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        // 确保宽度是8的倍数
        int newWidth = (width + 7) / 8 * 8;

        // 发送GS v 0命令
        outputStream.write(0x1D); // GS
        outputStream.write(0x76); // v
        outputStream.write(0x30); // 0
        outputStream.write(0x00); // m=0
        outputStream.write((newWidth / 8) & 0xFF); // xL
        outputStream.write((newWidth / 8) >> 8);   // xH
        outputStream.write(height & 0xFF);        // yL
        outputStream.write(height >> 8);           // yH

        // 发送位图数据
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < newWidth; x += 8) {
                byte slice = 0;
                for (int b = 0; b < 8; b++) {
                    int px = x + b;
                    int py = y;

                    int pixel;
                    if (px < width) {
                        pixel = bitmap.getPixel(px, py);
                    } else {
                        pixel = Color.WHITE; // 填充白色
                    }

                    // 如果像素是深色（非白色），设置为1
                    if (Color.red(pixel) < 128 && Color.green(pixel) < 128 && Color.blue(pixel) < 128) {
                        slice |= (byte) (1 << (7 - b));
                    }
                }
                outputStream.write(slice);
            }
        }
        // 恢复行间距
        outputStream.write(new byte[]{0x1B, 0x32});

        // 5. 打印页脚文本
        outputStream.write(new byte[]{0x1B, 0x61, 0x00}); // 左对齐
        if (footer != null && !footer.isEmpty()) {
            // 向右偏移2个字符位置打印页脚
            printTextWithOffset(footer, 2, false, false, outputStream);
        }

        // 换行和进纸
        outputStream.write(new byte[]{0x0A, 0x0A, 0x0A}); // 换行3次
//        outputStream.write(new byte[]{0x1D, 0x56, 0x42, 0x00}); // 切纸
        outputStream.flush();
    }

    // 设置绝对打印位置（以点为单位）
    private void setAbsolutePosition(int position, OutputStream outputStream) throws IOException {
        // ESC $ - 设置绝对打印位置
        // position: 0 ≤ position ≤ 65535 (点)
        outputStream.write(0x1B); // ESC
        outputStream.write(0x24); // $

        // 位置参数（低位在前，高位在后）
        int nL = position % 256;
        int nH = position / 256;

        outputStream.write(nL); // nL
        outputStream.write(nH); // nH
    }

    // 打印文本内容（向右偏移指定字符数）
    private void printTextWithOffset(String text, int offset,
                                     boolean centered, boolean large, OutputStream outputStream) throws IOException {
        // 计算偏移量（每个字符约12点）
        int dotOffset = offset * 12;

        // 设置绝对位置
        setAbsolutePosition(dotOffset, outputStream);

        // 打印文本
        printText(text, centered, large, outputStream);
    }

    // 打印文本内容（支持UTF-8）
    private void printText(String text, boolean centered, boolean large, OutputStream outputStream) throws IOException {
//        outputStream.write(new byte[]{0x0A, 0x0A}); // 换行2次
        // 设置文本样式
        if (centered) {
            outputStream.write(new byte[]{0x1B, 0x61, 0x01}); // 居中
        } else {
            outputStream.write(new byte[]{0x1B, 0x61, 0x00}); // 左对齐
        }

        if (large) {
            outputStream.write(new byte[]{0x1D, 0x21, 0x11}); // 双倍大小
        }

        // 转换为UTF-8字节数组并发送
//        byte[] textBytes = text.getBytes(StandardCharsets.UTF_8);
        // 转换为GBK字节数组并发送
        byte[] textBytes = text.getBytes(GBK_CHARSET);
        outputStream.write(textBytes);

        // 重置样式
        if (large) {
            outputStream.write(new byte[]{0x1D, 0x21, 0x00}); // 正常大小
        }
    }

    // 设置GBK编码的关键方法
    private void setGbkEncoding(OutputStream outputStream) throws IOException {
        try {
            // 使用标准ESC/POS指令设置GBK编码
            outputStream.write(new byte[]{0x1B, 0x74, 0x0F});
        } catch (Exception e) {
            Log.d("Printer", "标准GBK设置指令失败", e);
        }
    }

    // 设置UTF-8编码的关键方法
    private void setUtf8Encoding(OutputStream outputStream) throws IOException {
        // 方法1：使用标准ESC/POS指令设置UTF-8
        try {
            // 设置字符编码为UTF-8
            outputStream.write(new byte[]{0x1B, 0x74, 0x0C}); // ESC t n (n=12 表示UTF-8)
        } catch (Exception e) {
            Log.d("Printer","标准UTF-8设置指令失败，尝试备选方案", e);

            // 方法2：备选方案 - 设置国际字符集为UTF-8
            try {
                outputStream.write(new byte[]{0x1B, 0x52, 0x08}); // ESC R n (n=8 表示UTF-8)
            } catch (Exception e2) {
                Log.d("Printer", "备选UTF-8设置指令失败", e);

                // 方法3：发送BOM标记（字节顺序标记）
                outputStream.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
            }
        }
    }

    private boolean checkConnection() {
        if (socket == null || !socket.isConnected()) {
            connectPrinter();
            return socket != null && socket.isConnected();
        }
        return true;
    }

    private void sendToPrinter(byte[] data) throws IOException {
        OutputStream os = socket.getOutputStream();
        os.write(data);
        os.flush();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    private void handleException(Exception e) {
        Log.e("Printer", "打印错误", e);
        runOnUiThread(() ->
                Toast.makeText(this, "打印失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
        try {
            if (socket != null) socket.close();
        } catch (IOException ex) {
            Log.e("Printer", "关闭连接失败", ex);
        }
        socket = null;
    }

    private byte[] concatBytes(byte[]... arrays) {
        int length = 0;
        for (byte[] array : arrays) length += array.length;
        byte[] result = new byte[length];
        int pos = 0;
        for (byte[] array : arrays) {
            System.arraycopy(array, 0, result, pos, array.length);
            pos += array.length;
        }
        return result;
    }

    private void showToast(String msg) {
        runOnUiThread(() ->
                Toast.makeText(this, msg, Toast.LENGTH_SHORT).show());
    }
    private void showMaterialResult(MaterialInfo materialInfo) {
        if (materialInfo == null) {
            Toast.makeText(this, "数据错误", Toast.LENGTH_SHORT).show();
            return;
        }
        this.selectedMaterial = materialInfo; // 保存选中物料
        LinearLayout resultLayout = findViewById(R.id.layout_query_result);
        resultLayout.setVisibility(View.VISIBLE);

        TextView tvCode = findViewById(R.id.tv_result_code);
        TextView tvName = findViewById(R.id.tv_result_name);
        TextView tvSpec = findViewById(R.id.tv_result_spec);

        tvCode.setText("编码：" + materialInfo.getCode());
        tvName.setText("名称：" + materialInfo.getName());
        tvSpec.setText("规格：" + materialInfo.getSpec());

        showPrintButton();
    }

    @Override
    protected void onResume() {
        super.onResume();
        editTextSearch.setText("");
    }
}
